package com.ruoyi.my.controller.util;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.my.domian.util.baidutranslation.TransResult;
import com.ruoyi.my.domian.util.baidutranslation.TranslateParam;
import com.ruoyi.my.domian.util.baidutranslation.TranslateResult;
import com.ruoyi.my.utils.util.baidutranslationutil.GsonUtils;
import com.ruoyi.my.utils.util.baidutranslationutil.HttpUtil;
import com.ruoyi.my.utils.util.baidutranslationutil.OauthTokenUtil;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/util/baidutranslation")
public class BaiduTranslation {

    @Autowired
    private ISysDictDataService iSysDictDataService;

    /**
     * 翻译
     */
    @PreAuthorize("@ss.hasPermi('util:category:translate')")
    @GetMapping("/translate")
    public AjaxResult translate(TranslateParam translateParam) {
        String apiKey = iSysDictDataService.selectDictLabel("baidutranslation","apiKey");
        String securityKey = iSysDictDataService.selectDictLabel("baidutranslation","securityKey");
        String translateUrl = iSysDictDataService.selectDictLabel("baidutranslation","translateUrl");
        String tokenUrl = iSysDictDataService.selectDictLabel("baidutranslation","tokenUrl");;
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("from", translateParam.getFrom());
            map.put("to", translateParam.getTo());
            map.put("q", translateParam.getQ());
            String param = GsonUtils.toJson(map);
            String result = HttpUtil.post(translateUrl, OauthTokenUtil.getAccessToken(apiKey,securityKey,tokenUrl), "application/json", param);
            TranslateResult translateResult = JSONObject.parseObject(result,TranslateResult.class);
            if(translateResult != null && translateResult.getResult() != null){
                TransResult[] r = translateResult.getResult().getTrans_result();
                StringBuilder res = new StringBuilder();
                for(TransResult transResult: r){
                    res.append(transResult.getDst()).append("\n");
                }
                return AjaxResult.success(200,"完成翻译！", res.toString());
            } else {
                assert translateResult != null;
                return AjaxResult.success(201,"翻译失败！",translateResult.getError_code());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }



}
